package com.ztewatch.wearcontacts;

import java.util.ArrayList;

import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog.Calls;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.ztewatch.wearcontacts.calllog.CallLogAdapter;
import com.ztewatch.wearcontacts.calllog.CallLogQuery;

public class WearContactCallLogActivity extends Activity implements
		OnItemClickListener {
	private ListView mListView;
	private CallLogAdapter mCallLogAdapter;
	private TextView m_empty_view;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contact_call_log);

		initview();
	}

	private void initview() {
		mListView = (ListView) findViewById(R.id.call_log_list);
		mCallLogAdapter = new CallLogAdapter(this);
		mListView.setAdapter(mCallLogAdapter);
		mListView.setOnItemClickListener(this);
		m_empty_view = (TextView) findViewById(R.id.call_log_empty_view);
	}

	private final LoaderCallbacks<Cursor> loaderCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
			mCallLogAdapter.changeCursor(c);
			if (c.getCount() == 0) {
				m_empty_view.setVisibility(View.VISIBLE);
			} else {
				m_empty_view.setVisibility(View.GONE);
			}
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			markNewCallsAsOld();
			CursorLoader cursorLoader = new CursorLoader(WearContactCallLogActivity.this);
			configCursorLoader(cursorLoader, -1, false, -1);
			return cursorLoader;
		}
	};

    private void configCursorLoader(CursorLoader cursorLoader, int callType, boolean newOnly, long newerThan) {
		Uri uri = Calls.CONTENT_URI
				.buildUpon()
				.appendQueryParameter(Calls.LIMIT_PARAM_KEY,
						Integer.toString(1000)).build();
		
        StringBuilder where = new StringBuilder();
        ArrayList<String> selectionArgs = new ArrayList<String>();

        if (newOnly) {
            where.append(Calls.NEW);
            where.append(" = 1");
        }

        if (callType > -1) {
            if (where.length() > 0) {
                where.append(" AND ");
            }
            // Add a clause to fetch only items of type voicemail.
            where.append(String.format("(%s = ?)", Calls.TYPE));
            // Add a clause to fetch only items newer than the requested date
            selectionArgs.add(Integer.toString(callType));
        }

        if (newerThan > 0) {
            if (where.length() > 0) {
                where.append(" AND ");
            }
            where.append(String.format("(%s > ?)", Calls.DATE));
            selectionArgs.add(Long.toString(newerThan));
        }

        final String selection = where.length() > 0 ? where.toString() : null;
        cursorLoader.setUri(uri);
        cursorLoader.setSelection(selection);
        cursorLoader.setSelectionArgs(selectionArgs.toArray(new String[0]));
        cursorLoader.setProjection(CallLogQuery._PROJECTION);
        cursorLoader.setSortOrder(Calls.DEFAULT_SORT_ORDER);
    }
	
    private void markNewCallsAsOld() {
        StringBuilder where = new StringBuilder();
        where.append(Calls.NEW);
        where.append(" = 1");
        where.append(" AND ");
        //
        where.append(Calls.IS_READ).append(" = 0");
        where.append(" AND ");
        where.append(Calls.TYPE).append(" = ").append(Calls.MISSED_TYPE);
        //
        ContentValues values = new ContentValues(1);
        values.put(Calls.NEW, "0");
        values.put(Calls.IS_READ, "1");

        getContentResolver().update(Calls.CONTENT_URI, values, where.toString(), null);
    }
    
	@Override
	protected void onStart() {
		super.onStart();
		getLoaderManager().initLoader(0, null, loaderCallbacks);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getLoaderManager().destroyLoader(0);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Cursor cursor = (Cursor) mCallLogAdapter.getItem(position);
		if (cursor != null) {
			String number = cursor.getString(CallLogQuery.NUMBER);
			// Toast.makeText(this, number, Toast.LENGTH_SHORT).show();
			Uri uri = Uri.fromParts("tel", number, null);
			final Intent intent = new Intent(Intent.ACTION_CALL, uri);
			startActivity(intent);
		}
	}
}
